package com.guli.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.guli.oss.service.OssService;
import com.guli.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传文件到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // Endpoint以华东2（北京）为例
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件名称
        String filename = file.getOriginalFilename();
        //1.在文件名中添加唯一的随机值
        String uuid = UUID.randomUUID().toString();
        filename = uuid + filename;

        //把文件按照创建时间进行分类
        //获取当前时间
        String time = new DateTime().toString("yyyy/MM/dd");
        //拼接
        filename = time + "/" + filename;
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            //第一个参数：bucketName
            //第二个名称：上传到oss文件路径和名称
            ossClient.putObject(bucketName, filename, inputStream);
            //拼接路径
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            ossClient.shutdown(); //关闭资源流
        }
    }
}